#!/usr/bin/env python3
"""
创建Excel类型数据源测试脚本
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from sqlalchemy.orm import sessionmaker
from core.database import engine
from models.data_source import DataSource, ExcelConfig, DataSourceType, DataSourceStatus
from models.user import User
from datetime import datetime

def create_excel_data_source():
    """创建Excel类型数据源"""
    Session = sessionmaker(bind=engine)
    session = Session()
    
    try:
        # 获取默认用户
        default_user = session.query(User).filter(User.username == "user").first()
        if not default_user:
            print("未找到默认用户")
            return
        
        # 检查是否已存在Excel数据源
        existing_excel = session.query(DataSource).filter(DataSource.source_type == DataSourceType.EXCEL).first()
        if existing_excel:
            print(f"已存在Excel数据源: {existing_excel.name}")
            return
        
        # 创建Excel数据源
        excel_data_source = DataSource(
            name="测试Excel数据源",
            description="用于测试Excel文件上传功能",
            source_type=DataSourceType.EXCEL,
            status=DataSourceStatus.ACTIVE,
            creator_id=default_user.id,
            preview_enabled=True,
            preview_limit=10
        )
        
        session.add(excel_data_source)
        session.flush()  # 获取ID
        
        # 创建Excel配置
        excel_config = ExcelConfig(
            data_source_id=excel_data_source.id,
            file_path="D:\\WORKSPACES\\bowo\\xf_web\\test_excel_data.csv",
            file_name="test_excel_data.csv",
            file_size=152,  # 文件大小
            sheet_name="Sheet1",
            header_row=1,
            data_start_row=2,
            encoding="utf-8"
        )
        
        session.add(excel_config)
        session.commit()
        
        print(f"成功创建Excel数据源，ID: {excel_data_source.id}")
        print(f"数据源名称: {excel_data_source.name}")
        print(f"文件路径: {excel_config.file_path}")
        
    except Exception as e:
        session.rollback()
        print(f"创建数据源失败: {e}")
    finally:
        session.close()

if __name__ == "__main__":
    create_excel_data_source()